package spittr.web;


import java.io.File;
import java.io.IOException;

import javax.validation.Valid;
import javax.servlet.http.Part;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import spittr.Spitter;
import spittr.data.SpitterRepository;

@Controller
@RequestMapping("spitter")
public class SpitterController {

    private SpitterRepository spitterRepository;

    @Autowired
    public SpitterController(SpitterRepository spitterRepository) {
        this.spitterRepository = spitterRepository;
    }

    @GetMapping("register")
    public String showRegistrationForm(Model model) {
        model.addAttribute(new Spitter());
        return "registerForm";
    }


    @PostMapping("register")
    public String processRegistration(
            @RequestPart(value = "profilePicture", required = false) Part fileBytes,
            RedirectAttributes redirectAttributes,
            @Valid Spitter spitter,
            Errors errors) throws IOException {
        if (errors.hasErrors())
            return "registerForm";


        spitterRepository.save(spitter);
        System.out.println(fileBytes.getSize());
        fileBytes.write("d:/tmp/" + fileBytes.getSubmittedFileName());

        //RedirectAttributes是Model的一个子接口，提供了Model的所有功能
        redirectAttributes.addAttribute("username", spitter.getUsername());

        //除此之外，还有几个方法是用来设置flash属性的
        //flash属性会一直携带数据直到下一次请求结束
        //在重定向执行之前，所有的flash属性都会复制到会话中。
        //在重定向后，存在会话中的flash属性会被取出，并从会话转移到模型之中。
        redirectAttributes.addFlashAttribute(spitter);

        //username作为占位符填充到了URL模板中，username中所有的不安全字符都会进行转义
        //model中没有匹配重定向URL中的任何占位符的属性会自动以查询参数的形式附加到重定向URL上
        return "redirect:/spitter/{username}";
    }


    /*@PostMapping("register")
    public String processRegistration(
            @Valid SpitterForm spitterForm,
            Errors errors) throws IOException {

        if (errors.hasErrors())
            return "registerForm";

        Spitter spitter = spitterForm.toSpitter();
        spitterRepository.save(spitter);
        MultipartFile profilePicture = spitterForm.getProfilePicture();
        profilePicture.transferTo(new File("/tmp/spittr/" + spitter.getUsername() + ".jpg"));
        return "redirect:/spitter/" + spitter.getUsername();
    }*/

    @GetMapping("/{username}")
    public String showSpitterProfile(
            @PathVariable String username, Model model) {
        if (!model.containsAttribute("spitter"))//检查是否存有key为spitter的model属性
            model.addAttribute(spitterRepository.findByUsername(username));
        return "profile";
    }

}
